package com.tjetc.dao.impl;

import com.tjetc.dao.UserDao;
import com.tjetc.domain.User;
import com.tjetc.utils.Db;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    @Override
    public User getByPhone(String phone) throws SQLException {
        return Db.runner0().query("select * from user where phone = ?",new BeanHandler<>(User.class),phone);
    }

    @Override
    public void add(User user) throws SQLException {
        Db.runner0().update("insert into user(name,phone) values (?,?)",user.getName(),user.getPhone());
    }

    @Override
    public User getById(int id) throws SQLException {
        return Db.runner0().query("select * from user where id = ?",new BeanHandler<>(User.class),id);
    }

    @Override
    public void update(User user) throws SQLException {
        Db.runner().update(Db.getConnection(),"update user set account = ? where id = ?",
                user.getAccount(),user.getId());
    }

    @Override
    public void clearAccount(int id) throws SQLException {
        Db.runner0().update("update user set account = 0 where id = ?",id);
    }

    @Override
    public Integer getMaxId() throws SQLException {
        return Db.runner0().query("select max(id) from user",new ScalarHandler<>());
    }
}
